import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/main.vue'
import * as flow from '@/utils/flow.js'
// 布局
const mainRoutes = {
  path: '/',
  component: Layout,
  name: 'index',
  redirect: '/index',
  children: [
    {
      path: '/404',
      component: () => import('@/layout/404.vue')
    },
    {
      path: '/user-center',
      component: () => import('@/views/user-center/index.vue'),
      redirect: { path: '/user-center/uc-home' },
      children: []
    }
  ]
}

// 登录页
const loginPage = {
  path: '/login',
  name: 'login',
  component: () => import('@/common/login/index.vue')
}

// 注册页
const registerPage = {
  path: '/register',
  name: 'register',
  component: () => import('@/common/register/index.vue')
}

const forgetPasswordPage = {
  path: '/forget-password',
  name: 'forget-password',
  component: () => import('@/common/forget-password/index.vue')
}

// 客服页
const chatPage = {
  path: '/chat',
  name: 'chat',
  component: () => import('@/common/chat/index.vue')
}

// 客服页
const termsPage = {
  path: '/terms-page',
  name: 'terms-page',
  component: () => import('@/common/terms-page/index.vue')
}

// 根据本地目录，添加路由
const compModules = import.meta.glob('@/views/**/index.vue')
for (const [key, value] of Object.entries(compModules)) {
  // 过滤掉我的中心下的子路由
  if (!(key.indexOf('/src/views/user-center/') !== -1)) {
    mainRoutes.children.push({
      path: key.replace('/src/views', '').replace('/index.vue', ''),
      component: value
    })
  }
}

// 获取user-center下文件路径
const userCenterModules = import.meta.glob('@/views/user-center/**/index.vue')
for (const [key, value] of Object.entries(userCenterModules)) {
  // 过滤user-center/index
  if (key !== '/src/views/user-center/index.vue') {
    // 添加将获取到的路径作为路由添加到user-center下
    mainRoutes.children.filter(item => item.path === '/user-center')[0].children.push({
      path: key.replace('/src/views', '').replace('/index.vue', ''),
      component: value
    })
  }
}

const router = createRouter({
  history: createWebHistory(),
  routes: [
    mainRoutes,
    loginPage,
    registerPage,
    chatPage,
    termsPage,
    forgetPasswordPage
  ]
})

router.addRoute({ path: '/:pathMatch(.*)*', redirect: '/404' })

// eslint-disable-next-line no-unused-vars
router.beforeEach((to, from, next) => {
  // 初始化log数据
  if (!localStorage.getItem('bbcInitLog')) {
    localStorage.setItem('bbcInitLog', 'initLog')
    localStorage.setItem('bbcUuid', flow.getUuid())
    localStorage.setItem('bbcUuidSession', flow.getUuid())
    localStorage.setItem('bbcStep', 0)
    localStorage.setItem('bbcSessionTimeStamp', new Date().getTime())
  }
  // 操作间隔时间大于30分钟则更新 uuidSession(会话uuid),重置 step
  if ((new Date().getTime() - localStorage.getItem('bbcSessionTimeStamp')) / 1000 / 60 > 30) {
    localStorage.setItem('bbcUuidSession', flow.getUuid())
    localStorage.setItem('bbcStep', 0)
    localStorage.removeItem('bbcFlowAnalysisLogDto')
  }
  let step = localStorage.getItem('bbcStep') * 1
  // 获取页面信息
  const pageInfo = flow.getPageInfo(to)
  const flowAnalysisLogDto = {
    pageId: pageInfo.pageId,
    bizData: pageInfo.bizData,
    bizType: pageInfo.bizType,
    step,
    systemType: 1,
    uuid: localStorage.getItem('bbcUuid'),
    uuidSession: localStorage.getItem('bbcUuidSession'),
    visitType: 1,
    // userId: localStorage.getItem('bbcLoginResult') ? userId: localStorage.getItem('bbcLoginResult') ? JSON.parse(localStorage.getItem('bbcLoginResult')).userId : undefined,
    prevPageId: localStorage.getItem('bbcFlowAnalysisLogDto') ? JSON.parse(localStorage.getItem('bbcFlowAnalysisLogDto')).pageId : undefined
  }
  localStorage.setItem('bbcFlowAnalysisLogDto', JSON.stringify(flowAnalysisLogDto))
  if (pageInfo.pageId && (to.path != from.path || to.path === '/')) {
    step += 1
    flowAnalysisLogDto.step = step
    localStorage.setItem('bbcStep', step)
    localStorage.setItem('bbcFlowAnalysisLogDto', JSON.stringify(flowAnalysisLogDto))
    localStorage.setItem('bbcSessionTimeStamp', new Date().getTime()) // 更新会话时间
    flow.saveLog(flowAnalysisLogDto, 1)
  }
  const webConfigStore = useWebConfigStore()
  webConfigStore.getWebConfig()
  next()
})

export default router
